package com.zhx.threadcoreknowledge.threadobjectclasscommonmethod;

/**
 * @author ：zhanghaixuan
 * @date ：Created in 2019-10-03 16:57
 * 用途         ： 使用wait和notify交替答应0~100的奇偶数
 */
public class CountNumTo100Demo2 {

    private static CountNumTo100Demo2 self = new CountNumTo100Demo2();

    private int maxnum = 100;

    private static int count = 0;

    public static void main(String[] args) {
        PrintFunction printFunction = self.new PrintFunction();

        Thread manThread = new Thread(self.new ManThread(self.maxnum,printFunction),"奇数");
        Thread girlThread = new Thread(self.new GirlThread(self.maxnum,printFunction),"偶数");

        girlThread.start();
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        manThread.start();
    }

    class ManThread implements Runnable {
        private int maxnum;

        private PrintFunction print;

        public ManThread(int maxnum,PrintFunction print) {
            this.maxnum = maxnum;
            this.print = print;
        }

        @Override
        public void run() {
            while (count < maxnum) {
                while (count <= maxnum) {
                    print.print();
                }
            }
        }
    }

    class GirlThread implements Runnable {
        private int maxnum;

        private PrintFunction print;

        public GirlThread(int maxnum,PrintFunction print) {
            this.maxnum = maxnum;
            this.print = print;
        }

        @Override
        public void run() {
            while (count <= maxnum) {
                print.print();
            }
        }
    }

    class PrintFunction{
        public synchronized void print(){
            String name = Thread.currentThread().getName();

            if(name.equals("奇数") && (count &1)==1){
                System.out.println("奇数线程打印:" + count++);
                notify();
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if(name.equals("偶数") && (count &1)==0){
                System.out.println("偶数线程打印:" + count++);
                notify();
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
